<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket示例</title>
    <meta name="viewport"content="width=device-width,user-scalable=no,initial-scale=1.0,  maximum-scale=1.0,minimum-scale=1.0"> 
</head>
<body>
    <h1 id="success" style="display:none;">success</h1>
    <h1 id="error" style="display:none;">error</h1>
<script type="text/javascript">

    var webSocket = null;

    initSocket();

    function initSocket() {

        if (!"WebSocket" in window) {
            console.log("您的浏览器不支持 WebSocket!");
            return;
        }
        webSocket = new WebSocket("ws://"+document.domain +":8282");
        webSocket.onopen = handleSend;
        webSocket.onmessage = handleMessage;
        webSocket.onclose = handleClose;
        webSocket.onerror = handleError;
    }

    // 向服务器端发送数据
    function handleSend() {
        // document.write('success')
        document.getElementById('success').style.display = 'block'
        document.getElementById('error').style.display = 'none'
        // Web Socket 已连接上，使用 send() 方法发送数据
        // testing();
        ping()
    }

    var taskstate = 0
    var task = null

    function ping(){
        pingtask = setInterval(()=>{
            webSocket.send(JSON.stringify({'type':'ping'}));
            taskstate = 1
            task = setTimeout(()=>{
                if(taskstate == 1){
                    // 重连
                }
            }, 1000)
        }, 5000)
    }



    // 处理服务器端发送过来的数据
    function handleMessage(evt) {
        var received_msg = evt.data;
        console.log(received_msg);
        received_msg = JSON.parse(received_msg);
        // if(received_msg.type && received_msg.type == 'ping'){
        //     webSocket.send(JSON.stringify({'type':'ping'}));
        // }
        if(received_msg.type && received_msg.type == 'pong'){
            taskstate = 0
            clearTimeout(task)
        }
    }

    // 处理连接关闭事件
    function handleClose() {
        console.log("连接已关闭...");
    }

    // 处理WebSocket错误
    function handleError() {
        document.close()
        document.getElementById('success').style.display = 'none'
        document.getElementById('error').style.display = 'block'
        console.log("WebSocketError!");
    }

    function testing() {
        //每隔3秒钟向服务器发送数据，此处仅用于测试
        var items = ['张三','李四','小二黑','阿杜','单工','大理寺','花荣','刘备','诸葛亮'];
        setInterval(function () {
            var item = items[Math.floor(Math.random()*items.length)];
            webSocket.send(item);
        },3000);
    }

</script>
</body>
</html>